﻿<template>
  <span v-loading="isLoading">{{ nameMap[id]?nameMap[id]:id}}</span>
</template>
<script>
function noop() {
}

export default {
  name: "DataName",
  props: {
    //选中值
    value: {},
    //父级值
    parent: {},
    dataUrl: {},//数据接口
    data: {
      type: Array,
      default: () => {
        return []
      }
    },//数据列表
    //数据id属性
    valueKey: {
      type: String,
      default: 'id'
    },

  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      dataList: [],
      nameMap:{},
      isLoading: true,
    }
  },
  computed: {
    id: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit("change", value);
      }
    }
  },
  watch: {
    data() {
      this.loadDataList();
    },
    parent() {
      this.loadDataList();
    },
  },
  mounted() {
    this.loadDataList();
  },
  methods: {
    loadDataList: function () {
      this.isLoading = true;
      if (!this.dataUrl) {
        this.dataList = this.data;
        this.nameMap = this.getNameMap();
        this.$emit("load", this.dataList, this);
        this.isLoading = false;
        return;
      }
      let url = this.dataUrl;
      this.$get(url, {pageSize: -1}, (response) => {
        this.dataList = response.data;
        this.nameMap = this.getNameMap();
        this.$emit("load", response.data, this);
      }, () => {
        this.isLoading = false;
      })
    },
    getNameMap() {
      let map = {};
      for (let item of this.dataList) {
        map[item[this.valueKey]] = item.name;
      }
      return map;
    },
    getDataMap() {
      let map = {};
      for (let item of this.dataList) {
        map[item[this.valueKey]] = item;
      }
      return map;
    }
  }
};
</script>
